package com.project.controller.PurchaseController;

import com.github.pagehelper.PageInfo;
import com.project.bean.GoodsBean;
import com.project.bean.PurchaseOrderBean;
import com.project.bean.ShopCarBean;
import com.project.controller.shopController.ShopController;
import com.project.service.GoodsService.IGoodsService;
import com.project.service.PurchaseOrderService.IPurchaseOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.Map;

@RestController
@RequestMapping("/purchase")
public class PurchaseController {
    @Autowired
    private IPurchaseOrderService orderService;
    @Autowired
    private IGoodsService goodsService;

    @RequestMapping("/submit")
    public String addOrder(PurchaseOrderBean order, HttpServletRequest request) {
        Map<Integer, ShopCarBean> shopMap = (Map<Integer, ShopCarBean>) request.getSession().getAttribute("purchaseShopMap");
        if("".equals(shopMap.values()) || shopMap.size() == 0){
            return "no";
        }
        for(ShopCarBean s : shopMap.values()){
            if (goodsService.findById(s.getGoods().getId()) == null){
                s.getGoods().setStockNum(s.getNum());
                goodsService.addGoods(s.getGoods());
            }else {
                GoodsBean goods = goodsService.findById(s.getGoods().getId());
                goodsService.updateNumber(goods.getId(),s.getNum()+goods.getStockNum());
            }
        }
        orderService.addOrder(order,shopMap);
        shopMap.clear();
        return "ok";
    }

    @RequestMapping("/findById")
    public PurchaseOrderBean findById(int orderId) {
        return orderService.findById(orderId);
    }

    @RequestMapping("/findByItem")
    public PageInfo<PurchaseOrderBean> findByItem(int pageNO, String name, LocalDate startDate, LocalDate endDate) {
        return orderService.findByItem(pageNO, name, startDate, endDate);
    }
}
